# coding=utf-8
from flask import g
from flask_restful import Resource
from flask_restful.reqparse import RequestParser
from comment.ultils.decorators import Login_required
from comment.modules.account import Account
from comment.modules.deal_record import DealRecord
from comment.modules.user import User
from financial.resorces.account.serializer import AccountInfoSerializer
from comment.ultils.gen_trans_id import gen_trans_id
from financial.resorces.transaction.const import DealType
from comment.modules import db

class AccountInfo(Resource):

    '''拦截器看用户有没有登录过'''
    # 拦截器他会在LoginOut的所有的视图函数都会在执行视图函数之前，做一下装饰器的拦截
    method_decorators = [Login_required]  # 使用了登录拦截的装饰器

    def get(self):
        '''查询当前用户的资金账户'''
        user_id = g.user_id
        acc = Account.query.filter(Account.userId == user_id).first()

        if acc:
            return AccountInfoSerializer(acc).to_dict()
        else:
            return {
                'message':'资金账户不存在',
                'code':210
            }

class AccountExtract(Resource):

    '''拦截器看用户有没有登录过'''
    # 拦截器他会在LoginOut的所有的视图函数都会在执行视图函数之前，做一下装饰器的拦截
    method_decorators = [Login_required]  # 使用了登录拦截的装饰器

    def post(self): #提交表单
        '''提现的接口（有三个接口：1.选择银行卡 2.提取金额 3.支付密码）'''
        #验证码是由前端来进行验证的，后端不需要操作
        rp = RequestParser()
        rp.add_argument('amount', required=True, location="json") #金额
        rp.add_argument('card_id', required=True, location="json") #卡号
        rp.add_argument('payPwd', required=True, location="json") #支付密码

        args = rp.parse_args()

        amount = float(args.amount)
        card_id = args.card_id
        payPwd = args.payPwd

        user_id = g.user_id

        #查询当前登录的用户
        user = User.query.filter(User.id == user_id).first()

        if not user.check_pay_password(payPwd): #如果支付密码不一样的话
            return { #支付密码错误则返回
                'message':'支付密码错误',
                'code':211
            }

        #查询用户资金用户
        acc = Account.query.filter(Account.userId == user_id).first()
        if acc:
            if acc.balance < amount: #当前资金账户余额超出提现金额
                return {
                    'message':'超出提取的金额',
                    'code':212
                }
            else:
                #交易之前的金额
                before_balance = acc.balance
                #减少余额（修改新的余额）
                acc.balance = float(acc.balance) - amount
                #修改新的总金额
                acc.total = float(acc.total) - amount
                #生成交易的流水号（name代表使用枚举类的名字,value代表使用枚举类的值）
                deal_num = gen_trans_id(DealType.extract.name)
                '''提现:调用银行的接口来实现真正的提现'''

                #新增一条交易记录
                deal_log = DealRecord(aUserId=user_id, aReceiveOrPay=1, aTransferSerialNo=deal_num,
                                    aTransferStatus=1, aBeforeTradingMoney=before_balance, aAmount=amount,
                                    aAfterTradingMoney=acc.balance, aDescreption='提现',
                                    aType=DealType.extract.value)
                db.session.add(deal_log)
                db.session.commit()
                return {'msg': 'success'}

#充值
class AccountRecharge(Resource):
    '''资金账户的充值'''

    def post(self):
        rp = RequestParser()
        #传两个参数（1.选择银行来进行充值，2.充值金额）
        rp.add_argument('amount', required=True, location="json")
        rp.add_argument('selectedIndex', required=True, location="json")

        args = rp.parse_args()

        amount = float(args.amount)
        selected_bank_id  = args.selectedIndex

        user_id = g.user_id

        # 查询用户资金用户
        acc = Account.query.filter(Account.userId == selected_bank_id).first()
        if acc:
            # 交易之前的金额
            before_balance = acc.balance
            # 减少余额（修改新的余额）
            acc.balance = float(acc.balance) + amount
            # 修改新的总金额
            acc.total = float(acc.total) + amount
            # 生成交易的流水号（name代表使用枚举类的名字,value代表使用枚举类的值）
            deal_num = gen_trans_id(DealType.recharge.name)
            '''充值:调用银行的接口来实现真正的充值'''

            # 新增一条交易记录
            deal_log = DealRecord(aUserId=user_id, aReceiveOrPay=0, aTransferSerialNo=deal_num,
                                  aTransferStatus=1, aBeforeTradingMoney=before_balance, aAmount=amount,
                                  aAfterTradingMoney=acc.balance, aDescreption='充值',
                                  aType=DealType.recharge.value)
            db.session.add(deal_log)
            db.session.commit()
            return {'msg': 'success'}



